<?php
declare(strict_types=1);

namespace App\Task;

use App\Model\ContentItem;
use Carbon\Carbon;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * @Crontab(
 *     name="ContentItemStatus",
 *     rule="*\/5 * * * *",
 *     callback="execute",
 *     singleton=true,
 *     onOneServer=true,
 *     mutexPool="default",
 *     mutexExpires=60,
 *     memo="自动设置发布和下线"
 * )
 */
class ContentItemStatusTask
{
    public function execute(): void
    {
        /* 待发布 -> 已发布 */
        $models = ContentItem::query()
            ->select('id')
            ->where('status', '=', 3)
            ->whereNotNull('enable_start')
            ->where('enable_start', '<=', Carbon::now())
            ->getModels();
        $ids = [];
        /* @var ContentItem $model */
        foreach ($models as $model) {
            array_push($ids, $model->id);
        }
        if ($ids) {
            ContentItem::query(true)->whereIn('id', $ids)->update(['status' => 4]);
        }
        /* 已发布 -> 已下线 */
        $models = ContentItem::query()
            ->select('id')
            ->where('status', '=', 4)
            ->whereNotNull('enable_end')
            ->where('enable_end', '<=', Carbon::now())
            ->getModels();
        $ids = [];
        /* @var ContentItem $model */
        foreach ($models as $model) {
            array_push($ids, $model->id);
        }
        if ($ids) {
            ContentItem::query(true)->whereIn('id', $ids)->update(['status' => 5]);
        }
    }
}
